#!/bin/sh
#
# export -- export the vnc/ssh/webssh ports to internet
#
# Note: scripts/web-ubuntu.sh of https://github.com/tinyclub/cloud-ubuntu
#

TOP_DIR=$(cd $(dirname $0)/../../ && pwd)
. $TOP_DIR/tools/docker/config $* >/dev/null

CONTAINER_NAME=cloud-ubuntu-web
IMAGE_NAME=tinylab/$CONTAINER_NAME

[ -z "$PULL" ] && PULL=0

docker images | grep -q $IMAGE_NAME
[ $? -ne 0 -o $PULL -eq 1 ] && docker pull $IMAGE_NAME

DEFAULT_PORT_MAP=" -p $HOST_VNC_PORT:$CONTAINER_VNC_PORT -p $HOST_SSH_PORT:$CONTAINER_SSH_PORT -p $HOST_WEBSSH_PORT:$CONTAINER_WEBSSH_PORT "

# Available encrypt cmds: sha1sum, sha224sum, cksum, sha256sum, sha512sum, md5sum, sha384sum, sum
# To enable auto timeout, please pass VNC_TIMEOUT=1
[ -z "$VNC_TIMEOUT" ] && VNC_TIMEOUT=0
[ -z "$PROXY_LIMIT" ] && PROXY_LIMIT=0
[ -z "$ENCRYPT_CMD" ] && ENCRYPT_CMD="cat"
[ -n "$UNIX_PWD" ] && UNIX_PWD=`echo -n $UNIX_PWD | $ENCRYPT_CMD | cut -d' ' -f1`
[ -n "$VNC_PWD" ] && VNC_PWD=`echo -n $VNC_PWD | $ENCRYPT_CMD | cut -d' ' -f1`

# 16:10: 640x480 800x480 1280x800 1440x900 1680x1050 1920x1200 2560x1600
# 16:9: 960x540 1280x720 1920x1080 2560x1440
which xrandr >/dev/null 2>&1
[ $? -eq 0 -a -z "$SCREEN_SIZE" ] && SCREEN_SIZE=`xrandr --current | grep "^ .*\*" | tr -s ' ' | cut -d' ' -f2 | head -1`

[ -z "$SCREEN_SIZE" ] && SCREEN_SIZE=$DEF_SCREEN_SIZE
[ -z "$TOKEN_DIR" ] && TOKEN_DIR=$DEF_TOKEN_DIR
[ -z "$TOKEN_LENGTH" ] && TOKEN_LENGTH=$DEF_TOKEN_LENGTH
[ -z "$HOST_NAME" ] && HOST_NAME=localhost
[ -z "$UNIX_PWD" ] && UNIX_PWD=ubuntu
[ -z "$VNC_PWD" ] && VNC_PWD=ubuntu
[ -z "$PORT_MAP" ] && PORT_MAP="$DEFAULT_PORT_MAP"
[ -z "$ENV_ARGS" ] && ENV_ARGS=" -e VNC_TIMEOUT=$VNC_TIMEOUT -e UNIX_PWD=$UNIX_PWD -e VNC_PWD=$VNC_PWD -e SCREEN_SIZE=$SCREEN_SIZE -e PROXY_LIMIT=$PROXY_LIMIT -e NOSSL=$WEB_NOSSL"
[ -z "$EXTRA_ARGS" ] && EXTRA_ARGS=""

# Mount a directory for storing the noVNC recording sessions
[ -z "$VNC_RECORDINGS" ] && VNC_RECORDINGS=recordings
CONTAINER_RECORD_DIR=/noVNC/$VNC_RECORDINGS
HOST_RECORD_DIR=${TOP_DIR}/$VNC_RECORDINGS
[ ! -d $HOST_RECORD_DIR ] && mkdir -p $HOST_RECORD_DIR
VOLUME_MAP=" -v $HOST_RECORD_DIR:$CONTAINER_RECORD_DIR "
echo "LOG: VNC screen recorded in $HOST_RECORD_DIR"

LOCAL_TOKEN_DIR=${TOP_DIR}/${TOKEN_DIR}
REMOTE_TOKEN_DIR=/$TOKEN_DIR
VOLUME_MAP="$VOLUME_MAP -v $LOCAL_TOKEN_DIR:$REMOTE_TOKEN_DIR"

docker run \
	--name $CONTAINER_NAME --privileged -d -t \
	$PORT_MAP $VOLUME_MAP $ENV_ARGS $EXTRA_ARGS \
	-h $HOST_NAME $IMAGE_NAME
